package com.example.worldgdpjar.utils;

import com.example.worldgdpjar.dao.CountryDAO;
import com.example.worldgdpjar.model.CountryGDP;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

@Service
public class WorldBankApiClient {

  private final Logger logger = LoggerFactory.getLogger(getClass());

  private final Gson gson;
  private final CountryDAO countryDAO;

  private final String GDP_URL =
      "http://api.worldbank.org/countries/%s/indicators/NY.GDP.MKTP.CD?"
          + "format=json&date=2008:2019";

  public WorldBankApiClient(Gson gson, CountryDAO countryDAO) {
    this.gson = gson;
    this.countryDAO = countryDAO;
  }

  /*
   通过国家码查询该国历史GDP, 注意Json的解析
   https://jsoneditoronline.org/ Json在线解析
  */

  //  @Cacheable(value = "gdp", key = "#countryCode")
  public List<CountryGDP> getGDP(String countryCode) throws ParseException {

    //    logger.info("进入到http client查询阶段");
    String gdpStr = countryDAO.getGdp(countryCode);

    if (gdpStr != null) {
      // 反序列化
      Type listType = new TypeToken<List<CountryGDP>>() {}.getType();
      return gson.fromJson(gdpStr, listType);
    }

    RestTemplate worldBankRestTmplt = new RestTemplate();
    ResponseEntity<String> response =
        worldBankRestTmplt.getForEntity(String.format(GDP_URL, countryCode), String.class);

    // the second element is the actual data and its an array of object
    JSONParser parser = new JSONParser();
    // 将response转换为Array
    JSONArray responseData = (JSONArray) parser.parse(response.getBody());
    // 还是一个Array
    JSONArray countryDataArr = (JSONArray) responseData.get(1);

    List<CountryGDP> data = new ArrayList<>();
    JSONObject countryDataYearWise;
    // 遍历这个Array对象, 获取每个成员的各个属性
    for (Object o : countryDataArr) {
      countryDataYearWise = (JSONObject) o;

      String valueStr = "0";
      if (countryDataYearWise.get("value") != null) {
        valueStr = countryDataYearWise.get("value").toString();
      }
      String yearStr = countryDataYearWise.get("date").toString();
      CountryGDP gdp = new CountryGDP();
      gdp.setValue(valueStr != null ? Double.valueOf(valueStr) : null);
      gdp.setYear(Short.valueOf(yearStr));
      data.add(gdp);
    }

    countryDAO.updateGdp(countryCode, gson.toJson(data));
    return data;
  }
}
